package com.bio;

import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BioServer {

    public static void main(String[] args) throws Exception {

        // 创建一个线程池
        ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

        ServerSocket serverSocket = new ServerSocket(6666);

        System.out.println("服务器启动了");

        while (true){
            System.out.println("阻塞中...");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            cachedThreadPool.execute(() -> {
                handler(socket);
            });
        }
    }

    // 业务方法
    public static void handler(Socket socket){
        System.out.println("Tread-id:" + Thread.currentThread().getId());
        System.out.println("socket-id:" + socket.hashCode());
        byte[] bytes = new byte[1024];
            try{
                InputStream inputStream = socket.getInputStream();
                System.out.println("Thread".concat(String.valueOf((Thread.currentThread().getId()))).concat("从流中读取数据--开始"));

                while (true){
                    int read = inputStream.read(bytes);
                    if(read != -1){
                        System.out.print(new String(bytes));
                    }else{
                        break;
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                System.out.println("Thread".concat(String.valueOf((Thread.currentThread().getId()))).concat("从流中读取数据--结束"));

                try{
                    socket.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
    }
}
